// 加载处理库
import XLSX from 'xlsx'
import { emit } from '../services/socketio'
import { data_cols, data_cols2 } from '../../config/data'

export const export_xlsx = (data, filename) => {
    const wb = XLSX.utils.book_new();
    const jsonWs = XLSX.utils.json_to_sheet(data);
    // 将jsonWs 数据放入xlsx文件中的第二个tab，tab名为jsonWs
    XLSX.utils.book_append_sheet(wb, jsonWs, 'sheet1');
    XLSX.writeFile(wb, filename);
}

export const reset_tags = (state, dispatch) => {
    let tags = {}
    state.keys.forEach(key => {
        tags[key] = []
    })
    let file_data_cols = state.file_cols.map(i => i.title)

    dispatch({
        type: 'global/save',
        payload: {
            tag_bind: tags,
            file_data_cols: file_data_cols,
            format_file_data: []
        }
    })
}

export const upload_onChange = (info, state, dispatch) => {
    reset_tags(state, dispatch)

    dispatch({
        type: 'global/save',
        payload: {
            upload_file: info.file.name,
            file_cols: [],
            file_data: [],
            file_data_cols: [],
            format_file_data: [],
            sheet: '',
        }
    })
}

export const remov_file = (dispatch) => {
    dispatch({
        type: 'global/save',
        payload: {
            upload_file: '',
            file_cols: [],
            file_data: [],
            file_data_cols: [],
            format_file_data: [],
            workbook: null,
            sheet_names: [],
            sheet: '',
        }
    })
}

// 读取xlxs文件转json
export const xlsx_to_json = (jsonArr) => {
    // 获取表头信息
    let cols = jsonArr[0]
    let file_cols = cols.map(col => {
        console.log(col)
        col = col ? col : '-'
        return {
            title: col,
            dataIndex: col,
            key: col
        }
    })
    // 去除空值
    file_cols = file_cols.filter(f => f)

    // 获取数据
    let data = jsonArr.slice(1)
    data = data.filter(f => f.length !== 0)
    let file_data = data.map((it, id) => {
        let tmp = { key: id }
        cols.forEach((col, cid) => {
            tmp[col] = it[cid]
        })
        return tmp
    })
    let file_data_cols = cols

    console.log(file_data)

    return { file_cols, file_data, file_data_cols }
}

export const open_file = (file, dispatch) => {
    var reader = new FileReader();
    reader.onload = file => {
        console.log(file.name, 55)
        // 读入工作表
        var workbook = XLSX.read(file.target.result, { type: 'binary' })
        dispatch({
            type: 'global/save',
            payload: { workbook: workbook, sheet_names: workbook.SheetNames }
        })
    }
    // 读取文件
    reader.readAsBinaryString(file)
    return false;
}

export const open_sheet = (sheet, state, dispatch) => {
    var first_worksheet = state.workbook.Sheets[sheet]
    var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 })
    if (jsonArr.length === 0) return false

    dispatch({
        type: 'global/save',
        payload: {
            ...xlsx_to_json(jsonArr),
            sheet: sheet,
            format_file_data: []
        }
    })
}

export const format_json_xlsx = (state, dispatch) => {
    let keys = Object.keys(data_cols)

    let cols = [
        ...Object.keys(data_cols).map(c => c.title),
        ...Object.keys(data_cols2).map(c => c.title),
        '新增日期',
        '档案来源'
    ]



    // let sub_cols = { xzrq: get_date(), op: `工作表[${state.sheet}] 来自文件：${state.upload_file}` }
    // let keys = Object.keys(data_cols2)
    // keys.forEach(col => {
    //     sub_cols[col] = ''
    // })
    // let upload_file = rowkeys.map(id => {
    //     return { ...state.format_file_data[id], ...sub_cols }
    // })
    // dispatch({ type: 'global/save', payload: { upload_file_data: upload_file } })

    // return upload_file
}

// 格式化重复数据
export const format_repeat = (state, dispatch) => {
    var data = state.srowkey.map(id => {
        return { ...state.repeat_list[id] }
    })
    var cols = {}
    state.table_cols.forEach(row => {
        cols[row.key] = row.title
    });
    var format_data = data.map(row => {
        let keys = Object.keys(row)
        let col = {}
        keys.forEach(key => {
            if (cols[key]) col[cols[key]] = typeof row[key] ==='string'?row[key]:row[key].join(',')
        });
        return col
    })
    return format_data
}

// 格式化导出数据
export const format_list_all = (state, dispatch) => {
    var data = state.srowkey.map(id => {
        return { ...state.list_all[id] }
    })
    var cols = {}
    state.table_cols.forEach(row => {
        cols[row.key] = row.title
    });
    var format_data = data.map(row => {
        let keys = Object.keys(row)
        let col = {}
        keys.forEach(key => {
            if (cols[key]) col[cols[key]] = typeof row[key] ==='string'?row[key]:row[key].join(',')
        });
        return col
    })
    return format_data
}